package br.com.mtg.movethegarbage.graphics;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
import br.com.mtg.movethegarbage.framework.FileIO;
import br.com.mtg.movethegarbage.framework.Game;
import br.com.mtg.movethegarbage.framework.Graphics;

public class Texture
{

	public float width;
	public float height;

	int tex_id;
	int minFilter;
	int magFilter;

	Game game;
	Graphics graphics;
	String fileName;
	FileIO fileIO;

	public Texture(Game _game, String _fileName)
	{
		game = _game;
		graphics = game.getGraphics();
		fileName = _fileName;
		fileIO = game.getFileIO();

		load();
	}

	private void load()
	{
		InputStream in = null;
		int[] texID = new int[1];
		GL10 gl = graphics.getGL();

		gl.glGenTextures(1, texID, 0);
		tex_id = texID[0];

		try
		{
			in = fileIO.readAsset(fileName);
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			width = bitmap.getWidth();
			height = bitmap.getHeight();
			bind();
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
			setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST);
			unbind();

			bitmap.recycle();
		}
		catch (Exception e)
		{
			Log.e("Texture", "READ BITMAP ERROR");
		}
		finally
		{
			if (in != null)
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					Log.e("Texture", "CLOSE STREAM ERROR");
				}
		}
	}

	public void setFilters(int min, int mag)
	{
		minFilter = min;
		magFilter = mag;

		GL10 gl = graphics.getGL();
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, minFilter);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, magFilter);
	}

	public void reload()
	{
		load();
		bind();
		setFilters(GL10.GL_NEAREST, GL10.GL_NEAREST);
		unbind();
	}

	public void bind()
	{
		GL10 gl = graphics.getGL();
		gl.glBindTexture(GL10.GL_TEXTURE_2D, tex_id);
	}

	public void unbind()
	{
		GL10 gl = graphics.getGL();
		gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
	}

	public void dispose()
	{
		GL10 gl = graphics.getGL();
		bind();
		gl.glDeleteTextures(1, new int[] { tex_id }, 0);
		unbind();
	}
}
